package com.example.aop;

import cn.hutool.crypto.digest.DigestUtil;
import com.example.annotation.RepeatSubmit;
import com.example.enums.CodeEnum;
import com.example.exception.ServiceException;
import com.example.service.IUserService;
import com.example.utils.IpUtils;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.concurrent.TimeUnit;

/**
 * @Author 王鹤蒲
 * @Date 2023 10 25
 */

@Aspect
@Component
@Slf4j
public class RepeatSubmitAspect {

    @Resource
    private RedisTemplate redisTemplate;

    @Autowired
    private IUserService iUserService;

    @Pointcut("@annotation(repeatSubmit)")
    public void pointcutPreventRepeatSubmit(RepeatSubmit repeatSubmit) {

    }

    @Around("pointcutPreventRepeatSubmit(repeatSubmit)")
    public Object preventRepeatSubmit(ProceedingJoinPoint proceedingJoinPoint, RepeatSubmit repeatSubmit) throws Throwable {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        boolean res = false;
        long lockTime = repeatSubmit.lockTime();
        Integer userId = iUserService.getCurrentLoginUser().getUserId();
        String ipAddr = IpUtils.getIpAddr(request);
        MethodSignature methodSignature = (MethodSignature) proceedingJoinPoint.getSignature();
        Method method = methodSignature.getMethod();
        String className = method.getDeclaringClass().getName();
        String key = DigestUtil.md5Hex("repeat_submit:" + String.format("%s-%s-%s-%s", ipAddr, className, method, userId));
        res = redisTemplate.opsForValue().setIfAbsent(key, "1", lockTime, TimeUnit.SECONDS);
        if (!res) {
            log.error("请求重复提交");
            throw new ServiceException(CodeEnum.REQUEST_REPEAT_SUBMIT.getCode(), CodeEnum.REQUEST_REPEAT_SUBMIT.getMsg());
        }
        Object object = proceedingJoinPoint.proceed();
        return object;
    }
}
